package com.ross.springboot.service.impl;

import com.ross.springboot.entity.UserRole;
import com.ross.springboot.service.IUserRoleService;
import com.ross.springboot.shiro.MyShiroRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ross
 * @since 2020-07-24
 */
@Service
public class UserRoleServiceImpl extends BaseService<UserRole> implements IUserRoleService {

    @Autowired
    private MyShiroRealm myShiroRealm;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public void addUserRole(UserRole userRole) {
        //删除
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        mapper.deleteByExample(example);

        //添加
        String[] roleIds = userRole.getRoleId().split(",");
        for (String roleId : roleIds){
            UserRole u = new UserRole();
            u.setUserId(userRole.getUserId());
            u.setRoleId(roleId);
            mapper.insert(u);
        }

        //更新当前登录的用户的权限缓存
        List<Integer> userId = new ArrayList<>();
        userId.add(userRole.getUserId());
        myShiroRealm.clearUserAuthByUserId(userId);

    }
}
